$(function () {
    //输入框防抖
    var timer = null;

    // 优先从缓存中获取搜索建议
    // a.定义全局缓存对象
    var cacheObj = {};


    //定义防抖函数
    function debounceSearch(kw) {
        timer = setTimeout(function () {
            getSuggestList(kw);
        }, 500)
    }

    $('#iptSearch').on('keyup', function () {
        //清空timer
        clearTimeout(timer);
        var keywords = $(this).val().trim();
        if (keywords.length <= 0) {
            return $('#suggest-list').empty().hide();
        }
        //d.判断缓存中是否有数据
        if (cacheObj[keywords]) {
            return renderSuggestList(cacheObj[keywords]);
        }
        // getSuggestList(keywords);
        debounceSearch(keywords);
    })

    //发起JSONP请求
    function getSuggestList(kw) {
        $.ajax({
            url: 'http://suggest.taobao.com/sug?q=' + kw,
            dataType: 'jsonp',
            success: function (res) {
                renderSuggestList(res);
            }
        })
    }

    //渲染UI结构
    function renderSuggestList(res) {
        if (res.result.length <= 0) {
            return $('#suggest-list').empty().hide();
        }
        var htmlStr = template('tpl-suggestList', res);
        $('#suggest-list').html(htmlStr).show();

        //b.获取到用户输入的内容，当做键
        var k = $('#iptSearch').val().trim();
        //c.需要将数据作为值，进行缓存
        cacheObj[k] = res;
    }

})